﻿using System;
using System.Windows.Forms;

namespace AiMoRhino.ScriptInstance.LinkSelect
{
    partial class LinkedSelectForm : Form
    {
        readonly Linker owner;
        public LinkedSelectForm(Linker owner)
        {
            InitializeComponent();
            this.owner = owner;
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            owner.Items.Clear();
            owner.StopUpdate();
        }
        public void UpdateListItem()
        {
            if (InvokeRequired)
            {
                Invoke(new Action(UpdateListItem));
                return;
            }
            ItemListBox.Items.Clear();
            foreach (LinkedItemBase linkedItem in owner.Items)
                ItemListBox.Items.Add(linkedItem);
            ItemListBox.SelectedIndex = -1;
        }

        private void SelectButton_Click(object sender, EventArgs e)
        {
            if (ItemListBox.SelectedItem is LinkedItemBase item)
            {
                item.BuildLink();
                UpdateListItem();
                owner.UpdateRegisteredIds();
            }

        }

        private void UnselectButton_Click(object sender, EventArgs e)
        {
            if (ItemListBox.SelectedItem is LinkedItemBase item)
            {
                item.ClearLink();
                UpdateListItem();
                owner.UpdateRegisteredIds();
            }
        }

        private void UpdateCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            if (UpdateCheckBox.Checked)
            {
                owner.StartUpdate();
            }
            else
            {
                owner.StopUpdate();
            }
        }
    }
}
